package com.action.ui.fragment;


import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.action.childbase.ChildBaseFragment;
import com.action.entity.UserAliSncode;
import com.action.entity.UserHelper;
import com.action.entity.params.WithDepositParam;
import com.action.service.pressenter.MemberPressenter;
import com.action.ui.activity.QrcodeDialog;
import com.action.utils.SingleClick;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.app_core.App;
import com.base.app_core.model.Paginated;
import com.base.app_core.service.user.model.User;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.Preferences;
import com.base.app_core.util.XYBAUtils;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.StringUtils;
import com.tencent.mm.opensdk.modelbiz.JumpToBizProfile;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.xinglai.yun.R;
import com.xinglai.yun.wxapi.WXEntryActivity;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A simple {@link ChildBaseFragment} subclass.
 */
public class UserFrament extends ChildBaseFragment<MemberPressenter> {

    @BindView(R.id.user_head_image)
    ImageView userHeadImage;

    @BindView(R.id.user_name)
    TextView userName;

    @BindView(R.id.user_invite_count)
    TextView userInviteCount;

    @BindView(R.id.user_id)
    TextView userId;

    @BindView(R.id.version_code)
    TextView versionCode;

    public UserFrament() {
    }

    @Inject
    User user;

    @Inject
    WithDepositParam withDepositParam;

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    @Override
    protected void initView() {
        super.initView();
        setToolBar("");
        XYBAUtils.displayCircleImage(getActivity(), user.getWxIcon(), userHeadImage);
        userName.setText(user.getWxNickname());
        Long id = user.getId();
        if (id != null && id != 0) {
            userId.setText("id:" + String.valueOf(id));
        }
        userInviteCount.setText(user.getInviteCount() == null || user.getInviteCount() == 0 ? "" : user.getInviteCount() + "人");
//        versionCode.setText("v" + XYBAUtils.getVersion(getActivity()));
    }

    @Override
    protected boolean isNeedShowLoading() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mem;
    }

    @OnClick(R.id.bindaliaccount)
    public void bindAliAccount() {
        if (SingleClick.isSingle()) {
            if (XYBAUtils.checkApkExist(this.getActivity(), "com.tencent.mobileqq")){
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=274671450&version=1")));
            }else{
                showToast("本机未安装QQ应用");
            }
        }
    }


    @OnClick(R.id.loginout)
    public void loginOut() {
        MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
        builder.content("确定要退出？");
        builder.onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                showToast("退出");
                Preferences.putString(AppConstants.SP.JWTOKEN, null);
                Preferences.putString(AppConstants.SP.SNCODE, null);
                Preferences.putString(AppConstants.SP.JPUSH_KEY, null);
                Preferences.putString(AppConstants.SP.ALI_ACCOUNT, null);
                Preferences.putString(AppConstants.SP.USER_REALNAME, null);
                Preferences.putString(AppConstants.SP.MOBILE, null);
                withDepositParam.setRealName(null);
                withDepositParam.setAliAccount(null);
                user.setSnCode(null);
                user.setMobile(null);
                ActivityUtils.finishAllActivities();
                com.blankj.utilcode.util.ActivityUtils.finishAllActivities();
                FragmentActivity activity = getActivity();
                Intent intent = new Intent(activity, WXEntryActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(intent);
            }
        });
        builder.negativeText("取消");
        builder.positiveText("登出");
        builder.build().show();
    }

    @OnClick(R.id.qq_server)
    public void QQserverClick() {
        getQServer();
    }

    private void getQServer() {
        showProgress();
        mPresenter.fetchUserHelper();
    }

    private void goToWeChatServer() {
        IWXAPI api = App.getApp().iwxapi;
        if (api.isWXAppInstalled()) {
            JumpToBizProfile.Req req = new JumpToBizProfile.Req();
            req.toUserName = "wx9ec8ce350ec75d01"; // 公众号原始ID
            req.extMsg = "";
            req.profileType = JumpToBizProfile.JUMP_TO_NORMAL_BIZ_PROFILE; // 普通公众号
            api.sendReq(req);
        } else {
            Toast.makeText(getActivity(), "微信未安装", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        if (object instanceof UserHelper) {
            dismissProgress();
            UserHelper u = (UserHelper) object;
            QrcodeDialog qrcodeDialog = new QrcodeDialog(getActivity());
            qrcodeDialog.initView(u.getName(), u.getImage());
            qrcodeDialog.show();
        } else if (object instanceof UserAliSncode) {
            UserAliSncode aliSncode = (UserAliSncode) object;
            String aliAccount = aliSncode.getAliAccount();
            if (!StringUtils.isEmpty(aliAccount)) {
                Preferences.putString(AppConstants.SP.ALI_ACCOUNT, aliAccount);
                user.setAliAccount(aliAccount);
                withDepositParam.setAliAccount(aliAccount);
            }

            String userRealName = aliSncode.getUserRealName();
            if (!StringUtils.isEmpty(userRealName)) {
                Preferences.putString(AppConstants.SP.USER_REALNAME, userRealName);
                user.setRealName(userRealName);
                withDepositParam.setRealName(userRealName);
            }

            ARouter.getInstance().build(AppConstants.ROUTEURI.BINDALIACCOUNT).navigation();
        }
    }

    @Override
    public void notifyError(String errorCode, String content) {
        if (errorCode.equals("1068")) {
            //查无此支付宝账号信息
            user.setAliSnCode(null);
            ARouter.getInstance().build(AppConstants.ROUTEURI.BINDALIACCOUNT).navigation();
            return;
        }
        super.notifyError(errorCode, content);
    }


}
